package com.example.night.service.ApiService.Token;

import com.example.night.data.login.LoginResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.concurrent.locks.ReentrantLock;

@Service
public class TokenService {
    private static final Logger logger = LoggerFactory.getLogger(TokenService.class);
    private final RestTemplate restTemplate;
    private static final String LOGIN_URL = "https://api.jiutool.com/pc/login/accountLogin";
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final ReentrantLock lock = new ReentrantLock(); // 线程锁
    private final ApplicationEventPublisher eventPublisher;

    private String token;

    public TokenService(RestTemplate restTemplate, ApplicationEventPublisher eventPublisher) {
        this.restTemplate = restTemplate;
        this.eventPublisher = eventPublisher;
    }


    @PostConstruct
    @Scheduled(fixedRate = 10800000)
    public void init() {
        login("15651616098", "zhutao123");
    }

    public void login(String mobile, String password) {
        // 请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.set("Origin", "https://www.jiutool.com");
        headers.set("Referer", "https://www.jiutool.com/");
        headers.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36");

        // 表单数据
        String body = UriComponentsBuilder.newInstance()
                .queryParam("mobile", mobile)
                .queryParam("password", password)
                .build()
                .getQuery();

        // 构造请求体
        HttpEntity<String> requestEntity = new HttpEntity<>(body, headers);

        logger.info("Sending login request to: {}", LOGIN_URL);
        logger.info("Request body: {}", body);

        try {
            // 发送 POST 请求，先获取响应为 String
            ResponseEntity<String> response = restTemplate.exchange(LOGIN_URL, HttpMethod.POST, requestEntity, String.class);

            // 输出原始响应内容
            logger.info("Response body: {}", response.getBody());

            if (response.getStatusCode() == HttpStatus.OK) {
                // 如果返回的是JSON格式，可以手动解析
                String responseBody = response.getBody();
                // 假设响应是 JSON 格式的
                LoginResponse loginResponse = objectMapper.readValue(responseBody, LoginResponse.class);
                token = loginResponse.getData().getToken();
                eventPublisher.publishEvent(new TokenUpdatedEvent(this, this.token));
            } else {
                System.out.println("登录失败，状态码：" + response.getStatusCode());
            }
        } catch (Exception e) {
            logger.error("Login request failed: ", e);
        }
    }
    public String getToken() {
        return token;
    }
}
